package com.addressbook;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;

/**
 * @author zjs
 */
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.MyHolder> {
    private Context mContext;
    private List<Contacts> contactsList;


    public ContactsAdapter(Context mContext, List<Contacts> contactsList) {
        this.mContext = mContext;
        this.contactsList = contactsList;
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(mContext, R.layout.adapter_contacts_item, null);
        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder holder, int position) {
        holder.name.setText(contactsList.get(position).getName());
        holder.number.setText(contactsList.get(position).getNumber());
        holder.type.setText(contactsList.get(position).getType()+"");
        holder.label.setText(contactsList.get(position).getLabel());
        Glide.with(mContext).setDefaultRequestOptions(
                        new RequestOptions().frame(0)
                                .centerCrop())
                                .load(contactsList.get(position).getPhotoUri())
                                .into(holder.photoUri);
        holder.item.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:"+contactsList.get(position).getNumber()));
            mContext.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return contactsList.size();
    }


    class MyHolder extends RecyclerView.ViewHolder {
        private ImageView photoUri;
        private TextView name;
        private TextView number;
        private TextView type;
        private TextView label;
        private LinearLayout item;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            photoUri = itemView.findViewById(R.id.photoUri);
            name = itemView.findViewById(R.id.name);
            number = itemView.findViewById(R.id.number);
            type = itemView.findViewById(R.id.type);
            label = itemView.findViewById(R.id.label);
            item = itemView.findViewById(R.id.item);
        }
    }
}
